import json

from django import http
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU


class CartsView(View):

    def post(self, request):
        """添加购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)
        print("-------------------------")
        print("sku_id:",sku_id)
        print("count:",count)
        print("selected:",selected)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 3.1 登录 使用redis存储
        carts_redis_client = get_redis_connection('carts')

        user = request.user
        # 3.2 获取以前数据库的数据
        print("userid::",user.id)
        client_data = carts_redis_client.hgetall(user.id)
        print("client_data:",client_data)

        # 如果商品已经存在就更新数据
        if str(sku_id).encode() in client_data:
            # 根据sku_id 取出商品
            child_dict = json.loads(client_data[str(sku_id).encode()].decode())
            #  个数累加
            child_dict['count'] += count
            # 更新数据
            carts_redis_client.hset(user.id, sku_id, json.dumps(child_dict))

        else:
            # 如果商品已经不存在--直接增加商品数据
            carts_redis_client.hset(user.id, sku_id, json.dumps({'count': count, 'selected': selected}))

        return JsonResponse({'code': 0, 'errmsg': '添加购物车成功'})

    def get(self, request):
        """展示购物车"""

        # 1.用户已登录，查询redis购物车
        carts_redis_client = get_redis_connection('carts')

        # 2.获取当前用户的 所有购物车数据
        carts_data = carts_redis_client.hgetall(request.user.id)

        carts_dict = {int(key.decode()): json.loads(value.decode()) for key, value in carts_data.items()}

        sku_ids = carts_dict.keys()

        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,

                'count': carts_dict.get(sku.id).get('count'),
                'selected': carts_dict.get(sku.id).get('selected'),
            })

        return JsonResponse({'code': 0, 'errmsg': 'OK', 'cart_skus': cart_skus})

    def put(self, request):
        """修改购物车"""
        # 接收参数

        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        print("CartsView,put,sku_id,", sku_id)
        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品sku_id不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool值
        print("selected",selected)
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 1.链接 redis
        carts_redis_client = get_redis_connection('carts')
        # 2.覆盖redis以前的数据
        new_data = {'count': count, 'selected': selected}
        print("new_data",new_data)
        carts_redis_client.hset(request.user.id, sku_id, json.dumps(new_data))

        # 3.构建前端的json数据
        cart_sku = {
            'id': sku_id,
            'count': count,
            'selected': selected,
            'name': sku.name,
            'default_image_url': sku.default_image.url,
            'price': sku.price,
            'amount': sku.price * count,
        }
        response = JsonResponse({'code': 0, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})

        return response

    def delete(self, request):
        """删除购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')

        # 判断用户是否登录
        user = request.user
        # 用户登录，删除redis购物车
        carts_redis_client = get_redis_connection('carts')

        # 根据用户id 删除商品sku
        carts_redis_client.hdel(user.id, sku_id)

        # 删除结束后，没有响应的数据，只需要响应状态码即可
        return JsonResponse({'code': 0, 'errmsg': '删除购物车成功'})


class CartsSelectAllView(View):

    def put(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)

        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')
        # 判断用户是否登录
        user = request.user

        # 用户已登录，操作redis购物车
        carts_redis_client = get_redis_connection('carts')
        carts_data = carts_redis_client.hgetall(user.id)

        # 将所有商品的 选中状态修改
        for key, value in carts_data.items():
            sku_id = int(key.decode())
            carts_dict = json.loads(value.decode())

            # 修改所有商品的 选中状态
            carts_dict['selected'] = selected

            carts_redis_client.hset(user.id, sku_id, json.dumps(carts_dict))

        return JsonResponse({'code': 0, 'errmsg': '全选购物车成功'})

class CartsSimpleView(View):

    def get(self, request):
        user = request.user
        if user.is_authenticated:
            # 用户已登录，查询Redis购物车
            carts_redis_client = get_redis_connection('carts')
            user = request.user
            carts_data = carts_redis_client.hgetall(user.id)
            # 转换格式
            cart_dict = {int(key.decode()): json.loads(value.decode()) for key, value in carts_data.items()}

        else:
            pass
            # # 用户未登录，查询cookie购物车
            # cart_str = request.COOKIES.get('carts')
            # if cart_str:
            #     cart_dict = CookieSecret.loads(cart_str)
            # else:
            #     cart_dict = {}


class ABC(View):
    pass